import { defineComponent, onMounted, onUnmounted, reactive, watch } from "vue";
import styles from "./LoginPopup.module.less";
import { UserOutlined, LockOutlined, MobileOutlined, EyeOutlined } from "@ant-design/icons-vue";
import { useRouter, useRoute } from "vue-router";
import { $captcha } from "@/api/captcha/captcha";
import { message } from "ant-design-vue";
import validateInstance from "@/libs/validate/validate";
import { $login } from "@/api/login/login";
import { useStore as useUserStore } from "@/store/user";
import useCacheWhenTo from "@/hooks/useKeepAlive";
import eventBus from "@/common/mitt";

export default defineComponent({
  setup(props, { expose }) {
    // 设置缓存
    useCacheWhenTo(['forget']);
    const userStore = useUserStore();
    const router = useRouter();
    const route = useRoute();
    const state = reactive({
      isShow: false,
      navs: [
        {
          name: '用户密码登录',
          uid: '',
          password: '',
          showPassword: false,
          code: '',
          img: '',
          index_code: '',
        },
        // {
        //   name: '短信验证码登录',
        //   mobile: '',
        //   code2: '',
        //   syncCode: '',
        //   index_code2: '',
        // }
      ],
      nav_actived: 0,
      tips_show: {
        uid: false,
        password: false,
        code: false,
        mobile: false,
        code2: false,
        syncCode: false,
      },
    } as any)

    watch(() => state.isShow, (nv) => {
      if (!nv) {
        state.navs[0].uid = '';
        state.navs[0].password = '';
        state.navs[0].code = '';
        // state.navs[1].mobile = '';
        // state.navs[1].code2 = '';
        // state.navs[1].syncCode = '';
        state.nav_actived = 0;
      }
    })
    //获取图形验证图片
    const requestCode = () => {
      $captcha({
        scene: 'user.login'
      }).then((res: any) => {
        state.navs[0].img = res.data.img;
      })
    }
    // 打开弹窗
    const open = () => {
      state.isShow = true;
      requestCode();
    }
    // 确认登录
    const submit = () => {
      if (!validateInstance.test(state.navs[0].uid, "phone")) {
        message.error("手机号错误，请重新输入");
        return;
      }
      if (!state.navs[0].password) {
        message.error("请输入密码");
        return;
      }
      if (!state.navs[0].code) {
        message.error("请输入图形验证码");
        return;
      }
      $login({
        mobile: state.navs[0].uid,
        password: state.navs[0].password,
        captcha: state.navs[0].code,
      }).then((res: any) => {
        userStore.setToken(res.data?.token || '');
        userStore.setUid(res.data?.uid || '');
        message.success("登录成功");
        state.isShow = false;
        if (route.name === 'register') {
          state.isShow = false;
          router.replace('/')
        } else {
          window.location.reload();
        }
      }).catch((error: any) => {
        if (error.msg === '图文验证码过期或者不正确') {
          requestCode();
          state.navs[0].code = '';
        }
      })
    }
    // 验证输入
    const blurHandler = (key: string, index: number) => {
      if (!state.navs[index][key]) {
        state.tips_show[key] = true;
      } else {
        state.tips_show[key] = false;
      }
    }
    // 点击忘记密码跳转
    const forgetPassword = () => {
      router.push('/forget');
    }

    onMounted(() => {
      eventBus.loginLose.on(() => {
        open()
      });
    })

    onUnmounted(() => {
      eventBus.loginLose.off();
    })

    expose({
      open,
    })
    return () => (
      <div class={styles['login-floating']} v-show={state.isShow}>
        <div class={styles['card']}>
          <div class={styles['navs']}>
            {
              state.navs.map((item: any, index: number) => (
                <div class={[styles['nav'], index === state.nav_actived && styles.actived]} onClick={() => { }}>
                  {item.name}
                </div>
              ))
            }
          </div>
          <div class={styles.container}>
            <div class={styles['sign-rows']}>
              {
                state.nav_actived === 0 ? (
                  <>
                    <div class={styles['sign-row']}>
                      <div class={styles['sign-field']}>
                        <UserOutlined class={styles['field-icon']} />
                        <input v-model={state.navs[0].uid} placeholder="手机号/用户名" onBlur={() => { blurHandler('uid', 0) }} />
                      </div>
                    </div>
                    <span class={[styles.tips, state.tips_show.uid && styles.showTips]}>请输入手机号或用户名</span>
                    <div class={styles['sign-row']}>
                      <div class={styles['sign-field']}>
                        <LockOutlined class={styles['field-icon']} />
                        <input type={state.navs[0].showPassword ? 'text' : 'password'} v-model={state.navs[0].password} placeholder="密码" onBlur={() => { blurHandler('password', 0) }} />
                        <EyeOutlined class={[styles['field-icon'], styles.hoverable]} onClick={() => { state.navs[0].showPassword = !state.navs[0].showPassword }} />
                      </div>
                    </div>
                    <span class={[styles.tips, state.tips_show.password && styles.showTips]}>请输入密码</span>
                    <div class={styles['sign-row']}>
                      <div class={styles['sign-field']}>
                        <MobileOutlined class={styles['field-icon']} />
                        <input v-model={state.navs[0].code} placeholder="请输入图形验证码" onBlur={() => { blurHandler('code', 0) }} />
                      </div>
                      <div class={styles['code-img']}>
                        <img src={state.navs[0].img} onClick={() => { requestCode() }} />
                      </div>
                    </div>
                    <span class={[styles.tips, state.tips_show.code && styles.showTips]}>请输入图片验证码</span>
                    {/* <div class={styles['forget-password']} onClick={() => { router.push('/forget') }}>忘记密码</div>*/}
                  </>
                ) : (
                  <>
                    <div class={styles['sign-row']}>
                      <div class={styles['sign-field']}>
                        <input v-model={state.navs[1].mobile} placeholder="手机号" onBlur={() => { blurHandler('mobile', 1) }} />
                      </div>
                    </div>
                    <span class={[styles.tips, state.tips_show.mobile && styles.showTips]}>请输入手机号</span>
                    <div class={styles['sign-row']}>
                      <div class={styles['sign-field']}>
                        <MobileOutlined class={styles['field-icon']} />
                        <input v-model={state.navs[1].code2} placeholder="请输入图形验证码" onBlur={() => { blurHandler('code2', 1) }} />
                      </div>
                      <div class={styles['code-img']}>

                      </div>
                    </div>
                    <span class={[styles.tips, state.tips_show.code2 && styles.showTips]}>请输入图片验证码</span>
                    <div class={styles['sign-row']}>
                      <div class={styles['sign-field']}>
                        <input v-model={state.navs[1].syncCode} placeholder="请输入动态码" onBlur={() => { blurHandler('syncCode', 1) }} />
                      </div>
                      <div class={styles['send-btn']}>获取动态码</div>
                    </div>
                    <span class={[styles.tips, state.tips_show.syncCode && styles.showTips]}>请输入动态码</span>
                  </>
                )
              }
            </div>
            <div class={styles.footer}>
              <div class={styles['cancel-btn']} onClick={() => { state.isShow = false }}>
                取消
              </div>
              <div class={styles['submit-btn']} onClick={() => { submit() }}>
                确认登录
              </div>
            </div>
            <div class={styles['register-box']}>
              <div class={styles.registers}>
                <span>还没有账号？<span class={styles.register} onClick={() => { router.push('/register') }}>马上注册</span></span>
              </div>
              <div class={styles.forget} onClick={() => { forgetPassword() }}>忘记密码</div>
            </div>
          </div>
        </div>
      </div>
    )
  }
})